import {Component} from '@angular/core';
import {Events, PopoverController, ViewController, NavController} from 'ionic-angular';
import {UserDetailPage} from "../user-detail/user-detail";
import {User} from "../../providers/user";
import {AppData} from "../../providers/app-data";
import {Response} from "@angular/http";

@Component({
  template: `
    <ion-list>
      <button ion-item (click)="close()">添加新用户</button>
    </ion-list>
  `
})
class AddUserPopover {

  constructor(public events: Events, public viewCtrl: ViewController, public navCtrl: NavController) {
  }

  close() {
    this.viewCtrl.dismiss().then(()=> {
      var newUser: any;
      newUser = new User();
      newUser.id = "";
      newUser.name = "新用户";
      newUser.enabled = true;
      newUser.account = "";
      newUser.password = "";
      newUser.role = "view";
      this.events.publish('addUser:add', newUser);
    });//should wait dismiss() fully finished.

  }
}

@Component({
  templateUrl: 'build/pages/user-manage/user-manage.html'
})
export class UserManagePage {
  userList = [];

  constructor(public popoverCtrl: PopoverController, public navCtrl: NavController, public events: Events, public appData: AppData) {
    this.listenAddUserEvents();
  }

  listenAddUserEvents() {
    this.events.subscribe('addUser:add', (userArray) => {
      this.goToUserDetail(userArray[0]);
    });
  }

  goToUserDetail(user) {
    this.navCtrl.push(UserDetailPage, user);
  }

  ionViewDidEnter() {
    this.appData.getUserList().then((res: Response) => {
      this.userList = res.json().result;
    });
  }

  presentPopover(event) {
    let popover = this.popoverCtrl.create(AddUserPopover);
    popover.present({ev: event});
  }
}
